import time

from selenium.webdriver import ActionChains, Keys


class Bases:
    # driver = webdriver.Chrome()
    def __init__(self, driver):
        self.driver = driver

    # OpenChrome打开浏览器
    def open(self, url):
        self.driver.get(url)
        self.driver.maximize_window()
        self.wait(10)

    # Switch To New Window打开新标签页
    def open_new(self):
        self.driver.switch_to.new_window('tab')

    # Current Window Handle获取当前窗口页面的窗口句柄
    def NewHandles(self):
        time.sleep(3)
        first_window = self.driver.current_window_handle[0]
        new_window = self.driver.current_window_handle
        print('旧页面：' + first_window + '；切换定位新页面:' + new_window)
        time.sleep(2)

    # Find Element寻找元素定位
    def local(self, sid, value):
        self.wait(10)
        return self.driver.find_element(sid, value)

    # Click Element点击元素定位
    def click(self, sid, value):
        self.local(sid, value).click()
        print('点击元素：' + value)

    # 双击元素定位
    def double_click(self, sid, value):
        ActionChains(self.driver).double_click(self.local(sid, value)).perform()
        print('双击元素：' + value)

    # Input Element输入元素定位
    def input(self, sid, value, txt):
        b = self.local(sid, value)
        # 清除只读属性
        self.driver.execute_script('arguments[0].removeAttribute(\"readonly\")', b)
        b.clear()
        b.send_keys(txt)
        print('元素：' + value + '，输入：' + txt)

    # edit web excel编辑表格
    def edit(self, sid, value, txt):
        self.local(sid, value)
        time.sleep(1)
        ActionChains(self.driver).send_keys(txt).perform()
        print('元素：' + value + '，输入：' + txt)

    # imitate keyboard键盘操作
    def KeyBoard(self, sid, value, keys):
        self.local(sid, value).send_keys(keys)
        print('元素：' + value + '，键盘操作：' + keys)

    # find txt in page寻找指定文本是否在页面
    def wait_page(self, txt):
        time.sleep(2)
        if txt in self.driver.page_source:
            print(txt + '，等待5秒后再操作')
            time.sleep(5)
        else:
            print('检测不到：' + txt + '，自动化继续操作')

    # choice to pull down下拉框内容下移与回车
    def PullOption(self, sid, value):
        self.KeyBoard(sid, value, Keys.DOWN)
        self.KeyBoard(sid, value, Keys.ENTER)

    # pull to input text下拉框输入内容下移与回车
    def PullToInput(self, sid, value, txt):
        self.input(sid, value, txt)
        self.PullOption(sid, value)

    # Wait Element等待元素
    def wait(self, times):
        return self.driver.implicitly_wait(times)

    # 跳转上个页面
    def LastPage(self):
        self.driver.switch_to.window(self.driver.window_handles[0])

    # QuitChrome关闭浏览器
    def quit(self):
        self.driver.quit()
